<?php

namespace control;
/*
*科目余额表类
*/

class subjectBalanceClass extends adIndexClass
{
    private const page = 'subjectBalance';
    private const title = '科目余额表';
    public static bool $isFormat = false;//是否格式化数字
    public static bool $isExport = false;//是否导出

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array(
                        "name" => "createTime",
                        'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime($maxDate)) . ' ~ ' . date('Y-m',strtotime($maxDate)),
                        'laydate' => ['type' => 'month','range'=>'~','min'=>"'{$minDate}'",'max'=>"'{$maxDate}'"]
                    )),
                    '科目'  => componentClass::customSubject(['name' => 'formSubjectId','title' => '请选择']) . "-\n" .
                        componentClass::customSubject(['name' => 'toSubjectId','title' => '请选择']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = $this->pageButton();
        //返回
        return $this->homeFun($this->searchExecute([
            'html'         => $html,
            'layout'       => 'pop',
            'toolButton'   => $button,
            'option'      => '{fixed:true,row:2}'
        ]));
    }

    /**
     * 修改列表样式
     * @return bool|string
     */
    public function changeTableStyle(): bool|string
    {
        $style = $this->post('style');

        if (!in_array($style, accountDetailsClass::styleOption)) {
            $json['warn'] = '请选择列表样式';
        } else {
            $json['warn'] = 2;
            static::rSet(self::$stid . self::page . 'tableStyle', $style);
        }
        return json_encode($json, 320);
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        $style = static::rGet(self::$stid . self::page . 'tableStyle');
        if (empty($style)) {
            static::rSet(self::$stid . self::page . 'tableStyle', accountDetailsClass::styleOption[0]);
            $style = accountDetailsClass::styleOption[0];
        }
        static::rSet(self::$stid . self::page . 'tableStyle', $style);
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        if ($style == '金额式') {
            $json['html'] = $this->onlyMoneySearch();//金额式
        } else {
            $json['html'] = $this->moneyAndNumSearch();//数量金额式
        }
        $json['html'] .= $this->style();
        $json['html'] .= $this->js();
        return json_encode($json, 320);
    }

    /**
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.tableMany thead tr:nth-of-type(2) {  
    background-color: #f2f2f2;
    color: #555;  
}
</style>
eof;
    }
    /**
    }
     * @return string
     */
    public function js(): string
    {
        return <<<eof
<script>
$(function (){
    $(".total-tr").parent().parent().css('background-color','rgb(253, 238, 215)');
})
   function changeTableStyle(e){
       let val = e.value;
       $.post(root+'control/adIndex.html?cla=subjectBalance&fun=changeTableStyle',{style:val},function(res) {
            if (res.warn==2){
                location.reload();
            }else{
                msg(res.warn,'error')
            }
       },'json')
   }
   $("[name='yearSee[]']").on('click',function() {
       if ($(this).is(":checked")){
           setColumn(1);
       }else{
           setColumn(0);
       }
   })
   $(function() {
     styleColumn();
     $(".yellowBg").parent().css('background-color','#FDEED7')
   })
   function setColumn(val){
       $.post(root+'control/adIndex.html?cla=subjectBalance&fun=setColumn',{val:val},function(res) {
           styleColumn();
       },'json')
   }
   
   function styleColumn(){
       let style = $("#tabelStyle").val();
       if (style ==='数量金额式'){
           columnNumShow()
       }else{
           columnShow()
       }
   }
   /**
   * 金额式
   * */
   function columnShow(){
       if ($("[name='yearSee[]']").is(":checked")){
           $(".fixed-thead-head .tableMany thead tr").children("td").eq(4).css('display','table-cell');
           $(".fixed-thead-body .tableMany thead tr").children("td").eq(4).css('display','table-cell');
           $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(4).css('display','table-cell');
           $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(5).css('display','table-cell');
           $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(4).css('display','table-cell');
           $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(5).css('display','table-cell');
           $(".fixed-thead-body .tableMany tbody tr").each(function() {
               $(this).children("td").eq(6).css('display','table-cell');
               $(this).children("td").eq(7).css('display','table-cell');
           })
            $(".fixed-thead-head .tableMany tbody tr").each(function() {
               $(this).children("td").eq(6).css('display','table-cell');
               $(this).children("td").eq(7).css('display','table-cell');
           })
       }else{
           setTimeout(function() {
             $(".fixed-thead-head .tableMany thead tr").children("td").eq(4).css('display','none');
               $(".fixed-thead-body .tableMany thead tr").children("td").eq(4).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(4).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(5).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(4).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(5).css('display','none');
               $(".fixed-thead-body .tableMany tbody tr").each(function() {
                   $(this).children("td").eq(6).css('display','none');
                   $(this).children("td").eq(7).css('display','none');
               })
               $(".fixed-thead-head .tableMany tbody tr").each(function() {
                   $(this).children("td").eq(6).css('display','none');
                   $(this).children("td").eq(7).css('display','none');
               })
           },200)
       }
   }
    /**
   *  数量金额式
   * */
   function columnNumShow(){
         if ($("[name='yearSee[]']").is(":checked")){
           $(".fixed-thead-head .tableMany thead tr").children("td").eq(5).css('display','table-cell');
           $(".fixed-thead-body .tableMany thead tr").children("td").eq(5).css('display','table-cell');
           $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(8).css('display','table-cell');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(9).css('display','table-cell');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(10).css('display','table-cell');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(11).css('display','table-cell');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(8).css('display','table-cell');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(9).css('display','table-cell');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(10).css('display','table-cell');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(11).css('display','table-cell');
           $(".fixed-thead-body .tableMany tbody tr").each(function() {
                   $(this).children("td").eq(8).css('display','table-cell');
                   $(this).children("td").eq(9).css('display','table-cell');
                    $(this).children("td").eq(10).css('display','table-cell');
                   $(this).children("td").eq(11).css('display','table-cell');
               })
               $(".fixed-thead-head .tableMany tbody tr").each(function() {
                    $(this).children("td").eq(8).css('display','table-cell');
                   $(this).children("td").eq(9).css('display','table-cell');
                    $(this).children("td").eq(10).css('display','table-cell');
                   $(this).children("td").eq(11).css('display','table-cell');
               })
       }else{
           setTimeout(function() {
             $(".fixed-thead-head .tableMany thead tr").children("td").eq(5).css('display','none');
               $(".fixed-thead-body .tableMany thead tr").children("td").eq(5).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(8).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(9).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(10).css('display','none');
               $(".fixed-thead-head .tableMany thead").children("tr").eq(1).children("td").eq(11).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(8).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(9).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(10).css('display','none');
               $(".fixed-thead-body .tableMany thead").children("tr").eq(1).children("td").eq(11).css('display','none');
               $(".fixed-thead-body .tableMany tbody tr").each(function() {
                   $(this).children("td").eq(8).css('display','none');
                   $(this).children("td").eq(9).css('display','none');
                    $(this).children("td").eq(10).css('display','none');
                   $(this).children("td").eq(11).css('display','none');
               })
               $(".fixed-thead-head .tableMany tbody tr").each(function() {
                    $(this).children("td").eq(8).css('display','none');
                   $(this).children("td").eq(9).css('display','none');
                    $(this).children("td").eq(10).css('display','none');
                   $(this).children("td").eq(11).css('display','none');
               })
           },200)
       }
   }
</script>
eof;
    }

    public function setColumn(){
        $json['warn'] = 2;
        static::rSet(self::page.self::$stid.'Column',$this->post('val'));
        return json_encode($json, 320);
    }
    /**
     * 根据科目前缀对应企业会计准则分类
     * @return string
     */
    public static function typeByCode($code): string
    {
        $codeArr = array_flip(subjectClass::enterpriseCodePre());
        return $codeArr[$code[0]] ?? '';
    }

    /**
     * 数量金额式
     * @return string
     */
    public function moneyAndNumSearch(): string
    {
        $subjectText = '所有';
        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'a.isTemplate' => '否',
            'a.coid' => self::$coid
        );
        $and = "";
        if ($this->post('formSubjectId')) {
            $subjectSearch = query('subject', "id = '" . $this->post('formSubjectId') . "'");
            $subjectText = $subjectSearch['code'] . $subjectSearch['name'];
            $toSubject = query('subject', "id = '" . $this->post('toSubjectId') . "'");
            if ($toSubject['id']) {
                $subjectText .= "-" . $toSubject['code'] . $toSubject['name'];
            }
            $subjectObj = new subjectClass();
            $subjectIdArr = $subjectObj->getFromToSubject($this->post('formSubjectId'), $this->post('toSubjectId'));
            $and .= " and b.subjectId in ('" . implode("','", $subjectIdArr) . "')";
        }
        $arr        = $this->post('createTime') ? explode('~', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $arr[0] = trim($arr[0]);
        $arr[1] = trim(end($arr));
        $startMonth = trim($arr[0]);
        $endMonth = trim(end($arr));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and . "";
        $subjectWhere = search(array(
            '=' => array(
                'coid' => self::$coid,
                'id' => $this->post('subjectId')
            )
        ));
        if ($this->post('formSubjectId')) {
            $subjectIdArr = $subjectIdArr ?? [];
            $subjectWhere .= " and id in ('" . implode("','", $subjectIdArr) . "')";
        }
        $sql = " select * from subject where 1=1 ".$subjectWhere . " and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id= b.orderId where 1=1 " . $where . voucherClass::joinWhere() . ") or initMoney !=0)"." order by code asc";
        //获取查询结果
        $all = sqlFind($sql);
        static::rSet(self::$stid . self::page . 'sql', $sql);
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));
        $tr = [];
        $total = $tempTotal = [
            'initJieMoney' => 0,
            'initDaiMoney' => 0,
            'monthJieMoney' => 0,
            'monthDaiMoney' => 0,
            'yearJieMoney' => 0,
            'yearDieMoney' => 0,
            'balanceJieMoney' => 0,
            'balanceDieMoney' => 0,
        ];
        foreach ($all as $index=>$array) {
            if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
                continue;
            }
            //科目行
            $subjectRes = $this->getChildSubject($array['id']);
            $tr = array_merge($tr, $this->showNumTr($this->mergeSubject($subjectRes), $startMonth, $endMonth));
            //期初
            $initResult = $this->initMoney($array, $startMonth);
            //本期合计
            $monthResult = $this->monthBalance($startMonth, $endMonth, $array['id']);
            //期末余额
            $balanceResult = $this->balance($endMonth, $array['id']);
            /*if (empty(trim($initResult['jieMoney'])) && empty(trim($initResult['daiMoney'])) && empty(trim($monthResult['jieMoney'])) && empty(trim($monthResult['daiMoney'])) && empty(trim($balanceResult['jieBalance'])) && empty(trim($balanceResult['daiBalance']))) {
                continue;
            }*/
            //本年发生额
            $yearRes = $this->yearBalance($endMonth, $array['id']);
            $total['initJieMoney'] += $initResult['jieMoney'];
            $tempTotal['initJieMoney'] += $initResult['jieMoney'];

            $total['initDaiMoney'] += $initResult['daiMoney'];
            $tempTotal['initDaiMoney'] += $initResult['daiMoney'];

            $total['monthJieMoney'] += $monthResult['jieMoney'];
            $tempTotal['monthJieMoney'] += $monthResult['jieMoney'];

            $total['monthDaiMoney'] += $monthResult['daiMoney'];
            $tempTotal['monthDaiMoney'] += $monthResult['daiMoney'];

            $total['yearJieMoney'] += $yearRes['jieMoney'];
            $tempTotal['yearJieMoney'] += $yearRes['jieMoney'];

            $total['yearDieMoney'] += $yearRes['daiMoney'];
            $tempTotal['yearDieMoney'] += $yearRes['daiMoney'];

            $total['balanceJieMoney'] += $balanceResult['jieBalance'];
            $tempTotal['balanceJieMoney'] += $balanceResult['jieBalance'];

            $total['balanceDieMoney'] += $balanceResult['daiBalance'];
            $tempTotal['balanceDieMoney'] += $balanceResult['daiBalance'];
            // 科目分类小计
            if(!isset($all[$index+1]['code']) || (self::typeByCode($all[$index+1]['code']) != self::typeByCode($array['code']))){
                $tr[] = accountDetailsClass::formatArrayNumber([
                    ' ',
                    "<span class='total-tr'>".self::typeByCode($array['code'])."小计</span>",
                    ' ',
                    ' ',
                    ' ',
                    $tempTotal['initJieMoney'],
                    $tempTotal['initDaiMoney'],
                    ' ',
                    ' ',
                    $tempTotal['monthJieMoney'],
                    $tempTotal['monthDaiMoney'],
                    ' ',
                    ' ',
                    $tempTotal['yearJieMoney'],
                    $tempTotal['yearDieMoney'],
                    ' ',
                    ' ',
                    $tempTotal['balanceJieMoney'],
                    $tempTotal['balanceDieMoney']
                ]);
                $tempTotal = [
                    'initJieMoney' => 0,
                    'initDaiMoney' => 0,
                    'monthJieMoney' => 0,
                    'monthDaiMoney' => 0,
                    'yearJieMoney' => 0,
                    'yearDieMoney' => 0,
                    'balanceJieMoney' => 0,
                    'balanceDieMoney' => 0,
                ];
            }
        }
        $tr[] = accountDetailsClass::formatArrayNumber([
            ' ',
            "<span class='total-tr'>合计</span>",
            ' ',
            ' ',
            ' ',
            $total['initJieMoney'],
            $total['initDaiMoney'],
            ' ',
            ' ',
            $total['monthJieMoney'],
            $total['monthDaiMoney'],
            ' ',
            ' ',
            $total['yearJieMoney'],
            $total['yearDieMoney'],
            ' ',
            ' ',
            $total['balanceJieMoney'],
            $total['balanceDieMoney']
        ]);
        $table = $this->tableMany(['tr' => $tr, 'thead' => false]);
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html = <<<eof
<div class="finance-subject-head">科目：$subjectText {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle">科目编码</td>
            <td rowspan="2" style="vertical-align:middle">科目名称</td>
            <td rowspan="2" style="vertical-align:middle">计量单位</td>
            <td colspan="4" class="center">期初余额</td>
            <td colspan="4" class="center">本期发生金额</td>
             <td colspan="4" class="center">本年累计发生金额</td>
            <td colspan="4" class="center">期末余额</td></tr>
        <tr>
            <td>数量</td><td>单价</td><td>借方金额</td><td>贷方金额</td>
            <td>数量</td><td>单价</td><td>借方金额</td><td>贷方金额</td>
             <td>数量</td><td>单价</td><td>借方金额</td><td>贷方金额</td>
            <td>数量</td><td>单价</td><td>借方金额</td><td>贷方金额</td>
        </tr>
    </thead>
    <tbody>
       $table
    </tbody>
</table>
eof;
        //返回
        return
            "<div class='acct-main-container'>
                <form name='listForm'>" .
            $html .
            "</form>" .
            $monthSelector['html'].
            "</div>" .
            clear;
    }


    /**
     * 获取所有父级科目
     * @param $subjectId
     * @return array
     */
    public function getChildSubject($subjectId): array
    {
        $subject = query('subject', "id = '$subjectId'");
        if ($subject['pid'] != '0' && !empty($subject['pid'])) {
            $result[$subjectId] = $subject['pid'];
            $result = array_merge($result, $this->getChildSubject($subject['pid']));
        } else {
            $result[$subjectId] = '0';
        }
        return $result;
    }

    public function mergeSubject($subjectArr): array
    {
        $result = [];
        foreach ($subjectArr as $subjectId => $pid) {
            if ($pid == '0') {
                $result[] = $this->loopChild($subjectArr, $subjectId);
            }
        }
        return $result;
    }

    public function loopChild($subjectArr, $id): array
    {
        $result = [];
        $flag = false;
        foreach ($subjectArr as $subjectId => $pid) {
            if ($pid == $id) {
                $flag = true;
                $result['id'] = $id;
                $result['child'][] = $this->loopChild($subjectArr, $subjectId);
            }
        }
        if (!$flag) {
            $result = [
                'id' => $id,
                'child' => []
            ];
        }
        return $result;
    }

    public function showNumTr($result, $startMonth, $endMonth, $level = 0): array
    {
        $multiColumnAccountClass = new multiColumnAccountClass();
        $tr = [];
        $url = root . 'control/adIndex.html?cla=accountDetails&fun=home';
        foreach ($result as $array) {
            $subjectIds = [];
            $multiColumnAccountClass->loopSubjectIds($array['id'], $subjectIds);
            $subjectPid = query('subject', "id = '$array[id]'");//
            $jieInit = $daiInit = $jieMonth = $daiMonth = $jieBalance = $daiBalance = $jieYear = $daiYear = 0;
            $initNum = $monthNum = $balanceNum=$yearNum = 0;
            foreach ($subjectIds as $subjectId) {
                $subject = query('subject', "id = '$subjectId'");
                //期初
                $initResult = $this->initMoney($subject, $startMonth);
                //本期合计
                $monthResult = $this->monthBalance($startMonth, $endMonth, $subject['id']);
                //本年合计
                $yearResult = $this->yearBalance($endMonth, $subject['id']);
                //期末余额
                $balanceResult = $this->balance($endMonth, $subject['id']);
                $jieInit += $initResult['jieMoney'];
                $daiInit += $initResult['daiMoney'];
                $jieMonth += $monthResult['jieMoney'];
                $daiMonth += $monthResult['daiMoney'];
                $jieBalance += $balanceResult['jieBalance'];
                $daiBalance += $balanceResult['daiBalance'];
                $jieYear += $yearResult['jieMoney'];
                $daiYear += $yearResult['daiMoney'];
                $initNum += $initResult['num'];
                $monthNum += $monthResult['num'];
                $yearNum += $yearResult['num'];
                $balanceNum += $balanceResult['num'];
            }
            if ($jieInit == 0 && $daiInit == 0 && $jieMonth == 0 && $daiMonth == 0 && $jieBalance == 0 && $daiBalance == 0) {
                continue;
            }
            // 计算父级科目的总期初余额
            if ($jieInit > $daiInit) {
                $jieInit = $jieInit - $daiInit;
                $daiInit = 0;
            } else {
                $daiInit = $daiInit - $jieInit;
                $jieInit = 0;
            }
            // 计算父级科目的总期末余额
            if ($jieBalance > $daiBalance) {
                $jieBalance = $jieBalance - $daiBalance;
                $daiBalance = 0;
            } else {
                $daiBalance = $daiBalance - $jieBalance;
                $jieBalance = 0;
            }
            $interval = "";
            if (is_array($array['child']) && count($array['child']) > 0) {
                $subjectName = $subjectPid['name'];
                $initPrice = $monthPrice =$yearPrice= $balancePrice = 0;
            } else {
                $subjectName = self::$isExport ? $subjectPid['name'] : componentClass::urlTitle($subjectPid['name'], $url . "&id=" . $subjectPid['id'], '明细账');
                $initPrice = $initResult['price'] ?? 0;
                $monthPrice = $initResult['price'] ?? 0;
                $yearPrice = $initResult['price'] ?? 0;
                $balancePrice = $initResult['price'] ?? 0;
            }
            $interval .= str_repeat(self::$isExport ? " " : "&emsp;", $level);
            $tr[] = accountDetailsClass::formatArrayNumber([
                $interval . $subjectPid['code'],
                $interval . $subjectName,
                $subjectPid['numAccountText'],
                $initNum,
                $initPrice,
                $jieInit,
                $daiInit,
                $monthNum,
                $monthPrice,
                $jieMonth,
                $daiMonth,
                $yearNum,
                $yearPrice,
                $jieYear,
                $daiYear,
                $balanceNum,
                $balancePrice,
                $jieBalance,
                $daiBalance
            ], [0]);
            if (is_array($array['child']) && count($array['child']) > 0) {
                $tr = array_merge($tr, $this->showNumTr($array['child'], $startMonth, $endMonth, $level + 1));
            }
        }
        return $tr;
    }


    public function showTr($result, $startMonth, $endMonth, $level = 0): array
    {
        $multiColumnAccountClass = new multiColumnAccountClass();
        $tr = [];
        $url = root . 'control/adIndex.html?cla=accountDetails&fun=home';
        foreach ($result as $array) {
            $subjectIds = [];
            $multiColumnAccountClass->loopSubjectIds($array['id'], $subjectIds);

            $subjectPid = query('subject', "id = '$array[id]'");//
            $jieInit = $daiInit = $jieMonth = $daiMonth = $jieBalance = $daiBalance = $jieYear = $daiYear = 0;
            foreach ($subjectIds as $subjectId) {
                $subject = query('subject', "id = '$subjectId'");
                //期初
                $initResult = $this->initMoney($subject, $startMonth);
                //本期合计
                $monthResult = $this->monthBalance($startMonth, $endMonth, $subject['id']);
                //本年合计
                $yearResult = $this->yearBalance($endMonth, $subject['id']);
                //期末余额
                $balanceResult = $this->balance($endMonth, $subject['id']);
                $jieInit += $initResult['jieMoney'];
                $daiInit += $initResult['daiMoney'];
                $jieMonth += $monthResult['jieMoney'];
                $daiMonth += $monthResult['daiMoney'];
                $jieYear += $yearResult['jieMoney'];
                $daiYear += $yearResult['daiMoney'];
                $jieBalance += $balanceResult['jieBalance'];
                $daiBalance += $balanceResult['daiBalance'];
            }
            if ($jieInit == 0 && $daiInit == 0 && $jieMonth == 0 && $daiMonth == 0 && $jieBalance == 0 && $daiBalance == 0) {
                continue;
            }
            // 计算父级科目的总期初余额
            if ($jieInit > $daiInit) {
                $jieInit = $jieInit - $daiInit;
                $daiInit = 0;
            } else {
                $daiInit = $daiInit - $jieInit;
                $jieInit = 0;
            }
            // 计算父级科目的总期末余额
            if ($jieBalance > $daiBalance) {
                $jieBalance = $jieBalance - $daiBalance;
                $daiBalance = 0;
            } else {
                $daiBalance = $daiBalance - $jieBalance;
                $jieBalance = 0;
            }
            $interval = "";
            if (is_array($array['child']) && count($array['child']) > 0) {
                $subjectName = $subjectPid['name'];
            } else {
                $subjectName = self::$isExport ? $subjectPid['name'] : componentClass::urlTitle($subjectPid['name'], $url . "&id=" . $subjectPid['id'], '明细账','hands-url blue-font');
            }
            $interval .= str_repeat(self::$isExport ? " " : "&emsp;", $level);

            $tr[] = accountDetailsClass::formatArrayNumber([
                $interval . $subjectPid['code'],
                $interval . $subjectName,
                $jieInit,
                $daiInit,
                $jieMonth,
                $daiMonth,
                $jieYear,
                $daiYear,
                self::$isExport ? $jieBalance : $this->colorSpan($subjectPid['direction'],$jieBalance,0),
                self::$isExport ? $daiBalance : $this->colorSpan($subjectPid['direction'],0,$daiBalance),
            ], [0]);
            if (is_array($array['child']) && count($array['child']) > 0) {
                $tr = array_merge($tr, $this->showTr($array['child'], $startMonth, $endMonth, $level + 1));
            }
        }
        return $tr;
    }

    /**
     * 借贷金额与科目方向相反，则标为橘黄色
     */
    public function colorSpan($direction,$jieMoney,$daiMoney){
        if ($direction=='借'){
            //科目方向为借方
            if ($daiMoney !=0){
                return "<span class='yellowBg'>$daiMoney</span>";
            }
            return $jieMoney;
        }else{
            if ($jieMoney !=0){
                return "<span class='yellowBg'>$jieMoney</span>";
            }
            return $daiMoney;
        }
    }
    /**
     * 金额式
     */
    public function onlyMoneySearch(): string
    {
        $subjectText = '所有';

        //like查询数组
        $like = array();
        //全等查询数组
        $equal = array(
            'a.isTemplate' => '否',
            'a.coid' => self::$coid
        );
        $and = "";
        if ($this->post('formSubjectId')) {
            $subjectSearch = query('subject', "id = '" . $this->post('formSubjectId') . "'");
            $subjectText = $subjectSearch['code'] . $subjectSearch['name'];
            $toSubject = query('subject', "id = '" . $this->post('toSubjectId') . "'");
            if ($toSubject['id']) {
                $subjectText .= "-" . $toSubject['code'] . $toSubject['name'];
            }
            $subjectObj = new subjectClass();
            $subjectIdArr = $subjectObj->getFromToSubject($this->post('formSubjectId'), $this->post('toSubjectId'));
            $and .= " and b.subjectId in ('" . implode("','", $subjectIdArr) . "')";
        }
        $arr        = $this->post('createTime') ? explode('~', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $endMonth = trim(end($arr));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $subjectWhere = search(array(
            '=' => array(
                'coid' => self::$coid,
                'id' => $this->post('subjectId')
            )
        ));
        if ($this->post('formSubjectId')) {
            $subjectIdArr = $subjectIdArr ?? [];
            $subjectWhere .= " and id in ('" . implode("','", $subjectIdArr) . "')";
        }
        $sql = " select * from subject where 1=1 ".$subjectWhere . " and (id in (select distinct b.subjectId from voucher as a join voucher_detail as b on a.id= b.orderId where 1=1 " . $where . voucherClass::joinWhere() . ") or initMoney !=0)"." order by code asc";
        //获取查询结果
        $all = sqlFind($sql);
        $tr = [];
        static::rSet(self::$stid . self::page . 'sql', $sql);
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));
        //获取表头
        $total = $tempTotal = [
            'initJieMoney' => 0,
            'initDaiMoney' => 0,
            'monthJieMoney' => 0,
            'monthDaiMoney' => 0,
            'yearJieMoney' => 0,
            'yearDieMoney' => 0,
            'balanceJieMoney' => 0,
            'balanceDieMoney' => 0,
        ];
        foreach ($all as $index=>$array) {
            if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
                continue;
            }
            //科目行
            $subjectRes = $this->getChildSubject($array['id']);
            $tr = array_merge($tr,$this->showTr($this->mergeSubject($subjectRes), $startMonth, $endMonth));
            //合计
            //期初
            $initResult = $this->initMoney($array, $startMonth);
            //本期合计
            $monthResult = $this->monthBalance($startMonth, $endMonth, $array['id']);
            //期末余额
            $balanceResult = $this->balance($endMonth, $array['id']);
            /*if (empty(trim($initResult['jieMoney'])) && empty(trim($initResult['daiMoney'])) && empty(trim($monthResult['jieMoney'])) && empty(trim($monthResult['daiMoney'])) && empty(trim($balanceResult['jieBalance'])) && empty(trim($balanceResult['daiBalance']))) {
                continue;
            }*/
            //本年发生额
            $yearRes = $this->yearBalance($endMonth, $array['id']);
            $total['initJieMoney'] += $initResult['jieMoney'];
            $tempTotal['initJieMoney'] += $initResult['jieMoney'];

            $total['initDaiMoney'] += $initResult['daiMoney'];
            $tempTotal['initDaiMoney'] += $initResult['daiMoney'];

            $total['monthJieMoney'] += $monthResult['jieMoney'];
            $tempTotal['monthJieMoney'] += $monthResult['jieMoney'];

            $total['monthDaiMoney'] += $monthResult['daiMoney'];
            $tempTotal['monthDaiMoney'] += $monthResult['daiMoney'];

            $total['yearJieMoney'] += $yearRes['jieMoney'];
            $tempTotal['yearJieMoney'] += $yearRes['jieMoney'];

            $total['yearDieMoney'] += $yearRes['daiMoney'];
            $tempTotal['yearDieMoney'] += $yearRes['daiMoney'];

            $total['balanceJieMoney'] += $balanceResult['jieBalance'];
            $tempTotal['balanceJieMoney'] += $balanceResult['jieBalance'];

            $total['balanceDieMoney'] += $balanceResult['daiBalance'];
            $tempTotal['balanceDieMoney'] += $balanceResult['daiBalance'];
            // 科目分类小计
            if(!isset($all[$index+1]['code']) || (self::typeByCode($all[$index+1]['code']) != self::typeByCode($array['code']))){
                $tr[] = accountDetailsClass::formatArrayNumber([
                    ' ',
                    "<span class='total-tr'>".self::typeByCode($array['code'])."小计</span>",
                    $tempTotal['initJieMoney'],
                    $tempTotal['initDaiMoney'],
                    $tempTotal['monthJieMoney'],
                    $tempTotal['monthDaiMoney'],
                    $tempTotal['yearJieMoney'],
                    $tempTotal['yearDieMoney'],
                    $tempTotal['balanceJieMoney'],
                    $tempTotal['balanceDieMoney']
                ]);
                $tempTotal = [
                    'initJieMoney' => 0,
                    'initDaiMoney' => 0,
                    'monthJieMoney' => 0,
                    'monthDaiMoney' => 0,
                    'yearJieMoney' => 0,
                    'yearDieMoney' => 0,
                    'balanceJieMoney' => 0,
                    'balanceDieMoney' => 0,
                ];
            }
        }
        $tr[] = accountDetailsClass::formatArrayNumber([
            ' ',
            "<span class='total-tr'>合计</span>",
            $total['initJieMoney'],
            $total['initDaiMoney'],
            $total['monthJieMoney'],
            $total['monthDaiMoney'],
            $total['yearJieMoney'],
            $total['yearDieMoney'],
            $total['balanceJieMoney'],
            $total['balanceDieMoney']
        ]);
        $table = $this->tableMany(['tr' => $tr, 'thead' => false]);
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html = <<<eof
<div class="finance-subject-head">科目：$subjectText {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle">科目编码</td>
            <td rowspan="2" style="vertical-align:middle">科目名称</td>
            <td colspan="2" class="center">期初余额</td>
            <td colspan="2" class="center">本期发生金额</td>
            <td colspan="2" class="center">本年累计发生金额</td>
            <td colspan="2" class="center">期末余额</td>
        </tr>
        <tr>
            <td>借方</td><td>贷方</td>
            <td>借方</td><td>贷方</td>
            <td>借方</td><td>贷方</td>
            <td>借方</td><td>贷方</td>
        </tr>
    </thead>
    <tbody>
       $table
    </tbody>
</table>
eof;
        //返回
        return
            "<div class='acct-main-container'>
                <form name='listForm'>" .
            $html .
            "</form>" .
            $monthSelector['html'].
            "</div>" .
            clear;
    }

    /**
     *
     */
    public function pageButton()
    {
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton m-l-10'>导出</a>\n";
        }
        $button .= "<span class='m-l-10'></span>" . checkbox(['name' => 'yearSee', 'value' => [1 => '查看本年累计'], 'checked' => [static::rGet(self::page.self::$stid.'Column')?:0]]);
        return "<select id='tabelStyle' class='select'  onchange='changeTableStyle(this)'>" . option(array('value' => static::rGet(self::$stid . self::page . 'tableStyle'), 'option' => accountDetailsClass::styleOption)) . "</select>" . $button;
    }

    /**
     * 期初余额
     * @param $subject
     * @param $startMonth
     * @return array
     */
    public function initMoney($subject, $startMonth): array
    {
        //借方
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . voucherClass::joinWhere()));
        //贷方
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . voucherClass::joinWhere()));
        //期初数量
        $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $subject['initMoney'];
            $jieInit['num'] = $jieInit['num'] + $initNum;
        } else {
            $daiInit['num'] = $daiInit['num'] + $initNum;
            $daiInit['money'] += $subject['initMoney'];
        }
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        // 计算净余额
        $moneyDifference = $jieInit['money'] - $daiInit['money'];
        if ($subject['direction'] == '借') {
            if ($moneyDifference >= 0) {
                $jieMoney = $moneyDifference;
                $daiMoney = 0;
            } else {
                $jieMoney = 0;
                $daiMoney = abs($moneyDifference);
            }
        } else {
            if ($moneyDifference >= 0) {
                $jieMoney = 0;
                $daiMoney = $moneyDifference;
            } else {
                $jieMoney = abs($moneyDifference);
                $daiMoney = 0;
            }
        }

        // 计算数量差异和单价
        $numDifference = $jieInit['num'] - $daiInit['num'];
        $price = $numDifference != 0 ? abs(accountDetailsClass::division($moneyDifference, $numDifference)) : 0;

        // 准备结果数组
        $result = [
            'num' => voucherEditClass::formatZero($numDifference),
            'price' => $price,
            'jieMoney' => round($jieMoney, 2),
            'daiMoney' => round($daiMoney, 2)
        ];

        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 计算余额
     * @param $endMonth
     * @param $subjectId
     * @return array
     */
    public function balance($endMonth, $subjectId): array
    {
        $subject = query('subject', "id = '$subjectId'");
        //期初数量
        $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
        //期初金额
        $initMoney = $subject['initMoney'] ?: 0;
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . voucherClass::joinWhere()));
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
            $jieInit['num'] += $initNum;
        } else {
            $daiInit['money'] += $initMoney;
            $daiInit['num'] += $initNum;
        }
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            if ($jieInit['money'] > $daiInit['money']) {
                $jieBalance = $jieInit['money'] - $daiInit['money'];
                $daiBalance = 0;
            } else {
                $daiBalance = abs($jieInit['money'] - $daiInit['money']);
                $jieBalance = 0;
            }
            $balance = $jieInit['money'] - $daiInit['money'];
        } else {
            if ($daiInit['money'] > $jieInit['money']) {
                $daiBalance = $daiInit['money'] - $jieInit['money'];
                $jieBalance = 0;
            } else {
                $jieBalance = abs($daiInit['money'] - $jieInit['money']);
                $daiBalance = 0;
            }
            $balance = $daiInit['money'] - $jieInit['money'];
        }

        if ($subject['direction'] == '借') {
            $balanceNum = $jieInit['num'] - $daiInit['num'];
        } else {
            $balanceNum = $daiInit['num'] - $jieInit['num'];
        }
        $result = [
            'num' => voucherEditClass::formatZero($balanceNum),
            'price' => abs(accountDetailsClass::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'jieBalance' => round($jieBalance, 2),
            'daiBalance' => round($daiBalance, 2),
            'balance' => round($balance, 2),
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 本期合计
     */
    public function monthBalance($startMonth, $endMonth, $subjectId): array
    {
        $subject = query('subject', "id = '$subjectId'");
        $where = " and date_format(a.recordDate,'%Y-%m') >= '$startMonth' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借'" . $where . voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷'" . $where . voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            $balanceNum = $jieInit['num'] - $daiInit['num'];
        } else {
            $balanceNum = $daiInit['num'] - $jieInit['num'];
        }
        $result = [
            'num' => voucherEditClass::formatZero($balanceNum),
            'price' => abs(accountDetailsClass::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'jieMoney' => round($jieInit['money'], 2),
            'daiMoney' => round($daiInit['money'], 2),

        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 本年发生额
     */
    public function yearBalance($endMonth, $subjectId): array
    {
        $year = date('Y', strtotime($endMonth . '-01'));
        $subject = query('subject', "id = '$subjectId'");
        $where = " and date_format(a.recordDate,'%Y') = '$year'";
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借'" . $where . voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷'" . $where . voucherClass::joinWhere()));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            $balanceNum = $jieInit['num'] - $daiInit['num'];
        } else {
            $balanceNum = $daiInit['num'] - $jieInit['num'];
        }
        $result = [
            'num' => voucherEditClass::formatZero($balanceNum),
            'price' => abs(accountDetailsClass::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'jieMoney' => round($jieInit['money'], 2),
            'daiMoney' => round($daiInit['money'], 2),
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }


    /***导出数据处理***/
    public function exportDataHandle($data, $offset, $length){
        // 遍历每个子数组
        $newData = [];
        foreach ($data as $subArray) {
            // 删除索引为3和4的元素
            // array_splice(array &$input, int $offset, int $length = null, mixed $replacement = [])
            // $offset 是起始位置（基于0），$length 是要删除的元素数量
            array_splice($subArray, $offset, $length); // 从索引3开始，删除2个元素
            $newData[] = $subArray;
        }
        return $newData;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $style = static::rGet(self::$stid . self::page . 'tableStyle');
            if (empty($style)) {
                static::rSet(self::$stid . self::page . 'tableStyle', accountDetailsClass::styleOption[0]);
                $style = accountDetailsClass::styleOption[0];
            }
            static::rSet(self::$stid . self::page . 'tableStyle', $style);
            $time = static::rGet(self::$stid . self::page . 'time');
            $arr = $time ? explode(' ~ ', $time): [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
            $arr[0] = trim($arr[0]);
            $arr[1] = trim(end($arr));
            $startMonth = trim($arr[0]);
            $endMonth = trim(end($arr));
            $sql = static::rGet(self::$stid . self::page . 'sql');
            self::$isExport = true;

            $nowYear = static::rGet(self::page.self::$stid.'Column') ?: 0;  //是否显示本年累计
            if ($style == '金额式') {
                $title = array("科目编码", "科目名称", "借方期初余额", '贷方期初余额', "借方本期发生额", '贷方本期发生额', "借方本年发生额", '贷方本年发生额', '借方期末余额', '贷方期末余额');
                if(!$nowYear){
                    array_splice($title, 6, 2);
                }
                //获取查询结果
                $all = sqlFind($sql);
                $tr = [];
                $total = $tempTotal = [
                    'initJieMoney' => 0,
                    'initDaiMoney' => 0,
                    'monthJieMoney' => 0,
                    'monthDaiMoney' => 0,
                    'yearJieMoney' => 0,
                    'yearDaiMoney' => 0,
                    'balanceJieMoney' => 0,
                    'balanceDieMoney' => 0,
                ];
                foreach ($all as $index=>$array) {
                    if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
                        continue;
                    }
                    //科目行
                    $subjectRes = $this->getChildSubject($array['id']);
                    $tr = array_merge($tr, $this->showTr($this->mergeSubject($subjectRes), $startMonth, $endMonth));
                    //期初
                    $initResult = $this->initMoney($array, $startMonth);
                    //本期合计
                    $monthResult = $this->monthBalance($startMonth, $endMonth, $array['id']);
                    //本年合计
                    $yearResult = $this->yearBalance($endMonth, $array['id']);
                    //期末余额
                    $balanceResult = $this->balance($endMonth, $array['id']);
                    /*if (empty(trim($initResult['jieMoney'])) && empty(trim($initResult['daiMoney'])) && empty(trim($monthResult['jieMoney'])) && empty(trim($monthResult['daiMoney'])) && empty(trim($balanceResult['jieBalance'])) && empty(trim($balanceResult['daiBalance']))) {
                        continue;
                    }*/
                    $total['initJieMoney'] += $initResult['jieMoney'];
                    $tempTotal['initJieMoney'] += $initResult['jieMoney'];

                    $total['initDaiMoney'] += $initResult['daiMoney'];
                    $tempTotal['initDaiMoney'] += $initResult['daiMoney'];

                    $total['monthJieMoney'] += $monthResult['jieMoney'];
                    $tempTotal['monthJieMoney'] += $monthResult['jieMoney'];

                    $total['monthDaiMoney'] += $monthResult['daiMoney'];
                    $tempTotal['monthDaiMoney'] += $monthResult['daiMoney'];

                    $total['yearJieMoney'] += $yearResult['jieMoney'];
                    $tempTotal['yearJieMoney'] += $yearResult['jieMoney'];

                    $total['yearDaiMoney'] += $yearResult['daiMoney'];
                    $tempTotal['yearDaiMoney'] += $yearResult['daiMoney'];

                    $total['balanceJieMoney'] += $balanceResult['jieBalance'];
                    $tempTotal['balanceJieMoney'] += $balanceResult['jieBalance'];

                    $total['balanceDieMoney'] += $balanceResult['daiBalance'];
                    $tempTotal['balanceDieMoney'] += $balanceResult['daiBalance'];
                    // 科目分类小计
                    if(!isset($all[$index+1]['code']) || (self::typeByCode($all[$index+1]['code']) != self::typeByCode($array['code']))){
                        $tr[] = accountDetailsClass::formatArrayNumber([
                            ' ',
                            self::typeByCode($array['code']).'小计',
                            $tempTotal['initJieMoney'],
                            $tempTotal['initDaiMoney'],
                            $tempTotal['monthJieMoney'],
                            $tempTotal['monthDaiMoney'],
                            $tempTotal['yearJieMoney'],
                            $tempTotal['yearDaiMoney'],
                            $tempTotal['balanceJieMoney'],
                            $tempTotal['balanceDieMoney']
                        ]);
                        $tempTotal = [
                            'initJieMoney' => 0,
                            'initDaiMoney' => 0,
                            'monthJieMoney' => 0,
                            'monthDaiMoney' => 0,
                            'yearJieMoney' => 0,
                            'yearDaiMoney' => 0,
                            'balanceJieMoney' => 0,
                            'balanceDieMoney' => 0,
                        ];
                    }
                }

                if(!$nowYear){
                    $tr = $this->exportDataHandle($tr,6,2);
                }
                $total_tr = accountDetailsClass::formatArrayNumber([
                    ' ',
                    '合计',
                    $total['initJieMoney'],
                    $total['initDaiMoney'],
                    $total['monthJieMoney'],
                    $total['monthDaiMoney'],
                    $total['yearJieMoney'],
                    $total['yearDaiMoney'],
                    $total['balanceJieMoney'],
                    $total['balanceDieMoney']
                ]);
                if(!$nowYear){
                    array_splice($total_tr, 6, 2);
                }
                $tr[] = $total_tr;
            } else {
                $title = array("科目编码", "科目名称", '计量单位', '数量期初', '单价期初', "借方期初", '贷方期初', '数量本期发生', '单价本期发生', "借方本期发生额", '贷方本期发生额', '数量本年发生', '单价本年发生', "借方本年发生额", '贷方本年发生额', '数量期末', '单价期末', '借方期末余额', '贷方期末余额');
                if(!$nowYear){
                    array_splice($title, 11, 4);
                }
                $tr = [];
                $total = $tempTotal = [
                    'initJieMoney' => 0,
                    'initDaiMoney' => 0,
                    'monthJieMoney' => 0,
                    'monthDaiMoney' => 0,
                    'yearJieMoney' => 0,
                    'yearDaiMoney' => 0,
                    'balanceJieMoney' => 0,
                    'balanceDieMoney' => 0,
                ];
                $all = sqlFind($sql);
                foreach ($all as $index=>$array) {
                    if (static::total(array('table' => 'subject', 'where' => "pid = '$array[id]' and coid = '" . self::$coid . "'")) > 0) {
                        continue;
                    }
                    // 科目行
                    $subjectRes = $this->getChildSubject($array['id']);
                    $tr = array_merge($tr, $this->showNumTr($this->mergeSubject($subjectRes), $startMonth, $endMonth));
                    //期初
                    $initResult = $this->initMoney($array, $startMonth);
                    //本期合计
                    $monthResult = $this->monthBalance($startMonth, $endMonth, $array['id']);
                    //本年合计
                    $yearResult = $this->yearBalance($endMonth, $array['id']);
                    //期末余额
                    $balanceResult = $this->balance($endMonth, $array['id']);
                    /*if (empty(trim($initResult['jieMoney'])) && empty(trim($initResult['daiMoney'])) && empty(trim($monthResult['jieMoney'])) && empty(trim($monthResult['daiMoney'])) && empty(trim($balanceResult['jieBalance'])) && empty(trim($balanceResult['daiBalance']))) {
                        continue;
                    }*/
                    $total['initJieMoney'] += $initResult['jieMoney'];
                    $tempTotal['initJieMoney'] += $initResult['jieMoney'];

                    $total['initDaiMoney'] += $initResult['daiMoney'];
                    $tempTotal['initDaiMoney'] += $initResult['daiMoney'];

                    $total['monthJieMoney'] += $monthResult['jieMoney'];
                    $tempTotal['monthJieMoney'] += $monthResult['jieMoney'];

                    $total['monthDaiMoney'] += $monthResult['daiMoney'];
                    $tempTotal['monthDaiMoney'] += $monthResult['daiMoney'];

                    $total['yearJieMoney'] += $yearResult['jieMoney'];
                    $tempTotal['yearJieMoney'] += $yearResult['jieMoney'];

                    $total['yearDaiMoney'] += $yearResult['daiMoney'];
                    $tempTotal['yearDaiMoney'] += $yearResult['daiMoney'];

                    $total['balanceJieMoney'] += $balanceResult['jieBalance'];
                    $tempTotal['balanceJieMoney'] += $balanceResult['jieBalance'];

                    $total['balanceDieMoney'] += $balanceResult['daiBalance'];
                    $tempTotal['balanceDieMoney'] += $balanceResult['daiBalance'];
                    // 科目分类小计
                    if(!isset($all[$index+1]['code']) || (self::typeByCode($all[$index+1]['code']) != self::typeByCode($array['code']))){
                        $tr[] = accountDetailsClass::formatArrayNumber([
                            ' ',
                            self::typeByCode($array['code']).'小计',
                            ' ',
                            ' ',
                            ' ',
                            $tempTotal['initJieMoney'],
                            $tempTotal['initDaiMoney'],
                            ' ',
                            ' ',
                            $tempTotal['monthJieMoney'],
                            $tempTotal['monthDaiMoney'],
                            ' ',
                            ' ',
                            $tempTotal['yearJieMoney'],
                            $tempTotal['yearDaiMoney'],
                            ' ',
                            ' ',
                            $tempTotal['balanceJieMoney'],
                            $tempTotal['balanceDieMoney']
                        ]);
                        $tempTotal = [
                            'initJieMoney' => 0,
                            'initDaiMoney' => 0,
                            'monthJieMoney' => 0,
                            'monthDaiMoney' => 0,
                            'yearJieMoney' => 0,
                            'yearDaiMoney' => 0,
                            'balanceJieMoney' => 0,
                            'balanceDieMoney' => 0,
                        ];
                    }
                }
                if(!$nowYear){
                    $tr = $this->exportDataHandle($tr,11, 4);
                }
                $total_tr = accountDetailsClass::formatArrayNumber([
                    ' ',
                    '合计',
                    ' ',
                    ' ',
                    ' ',
                    $total['initJieMoney'],
                    $total['initDaiMoney'],
                    ' ',
                    ' ',
                    $total['monthJieMoney'],
                    $total['monthDaiMoney'],
                    ' ',
                    ' ',
                    $total['yearJieMoney'],
                    $total['yearDaiMoney'],
                    ' ',
                    ' ',
                    $total['balanceJieMoney'],
                    $total['balanceDieMoney']
                ]);
                if(!$nowYear){
                    array_splice($total_tr, 11, 4);
                }
                $tr[] = $total_tr;
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

